<script setup>
import { ref } from 'vue'
import { addOderService } from '@/api/borrowOrder.js'
import { useUserStore } from '@/stores'
const dialogVisible = ref(false)
const deposit = ref(1000)
const userStore = useUserStore()
const formRef = ref()
const inventory = ref(0)
const sinDeposit = ref(0)
const formModel = ref({
  username: '',
  bookId: '',
  num: 1,
  deposit: ''
})

const rules = {
  num: [
    { required: true, message: '请输入数量', trigger: 'change' },
    {
      pattern: /^[1-9]\d*$/,
      message: '数量必须是正整数',
      trigger: 'change'
    },
    {
      validator: (rule, value, callback) => {
        // 判断 value 和 当前 form 中收集的 password 是否一致
        if (value > inventory.value) {
          callback(new Error('数量超过库存数量'))
        } else {
          formModel.value.deposit = sinDeposit.value * value
          callback()
        }
      },
      trigger: 'change'
    }
  ]
}

const emit = defineEmits(['success'])
const onSubmit = async () => {
  await addOderService(formModel.value)
  dialogVisible.value = false
  emit('success')
}

// 组件对外暴露一个方法 open，基于open传来的参数，区分添加还是编辑
// open({})  => 表单无需渲染，说明是添加
// open({ id, cate_name, ... })  => 表单需要渲染，说明是编辑
// open调用后，可以打开弹窗
const open = (item) => {
  dialogVisible.value = true
  deposit.value = item.deposit
  formModel.value.username = userStore.username
  formModel.value.bookId = item.id
  sinDeposit.value = item.deposit
  formModel.value.deposit = item.deposit
  inventory.value = item.num
}
// 向外暴露方法
defineExpose({
  open
})
</script>

<template>
  <el-dialog v-model="dialogVisible" :title="'支付页面'" width="30%">
    <el-form
      ref="formRef"
      :model="formModel"
      :rules="rules"
      label-width="100px"
      style="padding-right: 30px"
    >
      <el-form-item label="库存数量">{{ inventory }} </el-form-item>
      <el-form-item label="借阅天数">30天 </el-form-item>
      <el-form-item label="借阅数量" prop="num"
        ><el-input v-model="formModel.num"></el-input
      ></el-form-item>
      <el-form-item label="需要支付的金额：" prop="deposit"
        >{{ formModel.deposit }}元
      </el-form-item>
      <el-form-item><el-button @click="onSubmit">下单</el-button></el-form-item>
    </el-form>
  </el-dialog>
</template>

<style lang="scss" scoped></style>
